<template>
  <view class="xen-material-detail">
    <!-- 头部 -->
    <view class="detail-header">
      <text class="header-title">选择型号（{{ material.Name }}）</text>
      <view class="close-btn" @click="handleClose">
        <uni-icons type="close" size="24" color="#fff" />
      </view>
    </view>

    <!-- 已选规格标签 -->
    <view v-if="selectedSpecs.length > 0" class="selected-specs-bar">
      <text class="bar-label">已选:</text>
      <view class="spec-tags">
        <view
          v-for="(spec, index) in selectedSpecs"
          :key="index"
          class="spec-tag"
        >
          <text class="tag-text">{{ spec.groupName }}:{{ spec.value }}</text>
          <view class="tag-close" @click="removeSpec(spec.groupName)">
            <uni-icons type="close" size="22" color="#7881de" />
          </view>
        </view>
      </view>
    </view>

    <!-- 型号列表 -->
    <scroll-view class="model-list-content" scroll-y>
      <view v-if="loading" class="loading-container">
        <uni-icons
          type="spinner-cycle"
          size="32"
          color="#7881de"
          class="loading-icon"
        />
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="modelGroups.length === 0" class="empty-container">
        <uni-icons type="info" size="48" color="#ccc" />
        <text class="empty-text">暂无型号数据</text>
      </view>

      <view v-else class="model-groups">
        <view
          v-for="(group, groupIndex) in modelGroups"
          :key="groupIndex"
          class="model-group"
        >
          <!-- 小标题 -->
          <view class="group-title">{{ group.Name }}</view>

          <!-- 型号列表 -->
          <view class="model-items">
            <view
              v-for="(model, modelIndex) in group.Values"
              :key="modelIndex"
              class="model-item"
              :class="{ selected: isModelSelected(group.Name, model.Value) }"
              @click="selectModel(group.Name, model.Value)"
            >
              <view class="model-radio">
                <view class="radio-outer">
                  <view
                    v-if="isModelSelected(group.Name, model.Value)"
                    class="radio-inner"
                  ></view>
                </view>
              </view>
              <text class="model-text">{{ model.Value }}</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="detail-footer">
      <button class="cancel-btn" @click="handleClose">取消</button>
      <button
        class="confirm-btn"
        @click="handleConfirm"
        :disabled="selectedSpecs.length === 0"
      >
        确定
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import commonApi from "@/api/common";
import type { ISysMaterial, ISysMaterialGroupQuery } from "./type/interface";

interface ModelValue {
  Value: string;
}

interface ModelGroup {
  Name: string;
  Values: ModelValue[];
  IsKeyAttribute?: boolean;
}

interface SelectedSpec {
  groupName: string;
  value: string;
}

interface Props {
  material: ISysMaterial;
  visible?: boolean;
  isKeyAttribute?: boolean; // 是否只显示关键属性
}

interface Emits {
  (e: "confirm", model: string): void;
  (e: "close"): void;
}

const props = withDefaults(defineProps<Props>(), {
  isKeyAttribute: false,
});
const emit = defineEmits<Emits>();

// API实例
const api = commonApi();

// 数据状态
const modelGroups = ref<ModelGroup[]>([]);
const loading = ref(false);
const selectedSpecs = ref<SelectedSpec[]>([]);

// 加载物料组列表（型号数据）
const loadModelGroups = async () => {
  if (!props.material.ID) return;

  loading.value = true;
  try {
    const queryParams: ISysMaterialGroupQuery = {
      MaterialId: props.material.ID,
      Page: 1,
      Limit: 9999,
    };

    const response = await api.GetMaterialGroupList(queryParams);
    console.log("=== 物料组列表API响应 ===", response);

    // 注意：API返回的是 Data（大写D），不是 data（小写d）
    if (response && response.Data && Array.isArray(response.Data)) {
      // 转换数据格式并根据 isKeyAttribute 进行筛选
      let filteredData = response.Data;

      // 如果启用了关键属性筛选，只显示 IsKeyAttribute 为 true 的分组
      if (props.isKeyAttribute) {
        filteredData = response.Data.filter(
          (item: any) => item.IsKeyAttribute === true,
        );
        console.log("=== 关键属性筛选后的数据 ===", filteredData);
      }

      modelGroups.value = filteredData.map((item: any) => ({
        Name: item.Name || "默认分组",
        Values: item.Values || [],
        IsKeyAttribute: item.IsKeyAttribute || false,
      }));
      console.log("=== 物料组列表数据 ===", modelGroups.value);
    } else {
      console.warn("=== 物料组列表数据格式异常 ===", response);
    }
  } catch (error) {
    console.error("加载型号数据失败:", error);
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 选择型号（每个分组只能选一个）
const selectModel = (groupName: string, value: string) => {
  // 查找是否已经选择了这个分组
  const existingIndex = selectedSpecs.value.findIndex(
    (spec) => spec.groupName === groupName,
  );

  if (existingIndex !== -1) {
    // 如果已选择同一个分组，更新值
    selectedSpecs.value[existingIndex].value = value;
  } else {
    // 添加新的选择
    selectedSpecs.value.push({ groupName, value });
  }
};

// 判断某个型号是否被选中
const isModelSelected = (groupName: string, value: string) => {
  return selectedSpecs.value.some(
    (spec) => spec.groupName === groupName && spec.value === value,
  );
};

// 移除已选规格
const removeSpec = (groupName: string) => {
  selectedSpecs.value = selectedSpecs.value.filter(
    (spec) => spec.groupName !== groupName,
  );
};

// 确认选择
const handleConfirm = () => {
  if (selectedSpecs.value.length > 0) {
    // 将所有选中的规格组合成字符串，格式：值1-值2-值3
    const modelString = selectedSpecs.value.map((spec) => spec.value).join("-");
    emit("confirm", modelString);
  }
};

// 关闭
const handleClose = () => {
  emit("close");
};

// 组件挂载时加载数据
onMounted(() => {
  if (props.visible) {
    loadModelGroups();
  }
});

// 监听visible变化，重新加载数据
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      selectedSpecs.value = [];
      loadModelGroups();
    }
  },
);
</script>

<style lang="scss" scoped>
.xen-material-detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;

  .detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;

    .header-title {
      font-size: 18px;
      font-weight: 600;
    }

    .close-btn {
      padding: 4px;
      cursor: pointer;
    }
  }

  .selected-specs-bar {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 16px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;

    .bar-label {
      font-size: 13px;
      color: #666;
      white-space: nowrap;
    }

    .spec-tags {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 6px;

      .spec-tag {
        display: flex;
        align-items: center;
        gap: 4px;
        padding: 4px 8px;
        background: linear-gradient(135deg, #f0f0ff 0%, #f8f0ff 100%);
        border: 1px solid #e0d8ff;
        border-radius: 12px;
        font-size: 12px;

        .tag-text {
          color: #7881de;
          line-height: 1;
        }

        .tag-close {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 16px;
          height: 16px;
          cursor: pointer;
          border-radius: 50%;
          transition: background-color 0.2s;

          &:active {
            background-color: rgba(120, 129, 222, 0.1);
          }
        }
      }
    }
  }

  .model-list-content {
    flex: 1;
    height: 0; /* 关键：配合 flex: 1 使用，让 scroll-view 可以正确计算高度 */
    padding: 0 16px 16px;
    box-sizing: border-box;

    .loading-container,
    .empty-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 20px;
      color: #999;

      .loading-icon {
        animation: rotate 1s linear infinite;
      }

      .loading-text,
      .empty-text {
        margin-top: 12px;
        font-size: 14px;
      }
    }

    .model-groups {
      display: flex;
      flex-direction: column;
      gap: 16px;

      .model-group {
        background-color: #ffffff;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

        .group-title {
          padding: 12px 16px;
          font-size: 15px;
          font-weight: 600;
          color: #333;
          background-color: #f8f9fa;
          border-bottom: 1px solid #e0e0e0;
        }

        .model-items {
          padding: 8px;

          .model-item {
            display: flex;
            align-items: center;
            padding: 8px;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.2s;

            &:active {
              background-color: #f5f5f5;
            }

            &.selected {
              background-color: #f0f0ff;

              .model-text {
                color: #7881de;
                font-weight: 500;
              }
            }

            .model-radio {
              margin-right: 12px;

              .radio-outer {
                width: 20px;
                height: 20px;
                border: 2px solid #ddd;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: border-color 0.2s;
              }

              .radio-inner {
                width: 12px;
                height: 12px;
                background-color: #7881de;
                border-radius: 50%;
              }
            }

            &.selected .radio-outer {
              border-color: #7881de;
            }

            .model-text {
              flex: 1;
              font-size: 14px;
              color: #333;
            }
          }
        }
      }
    }
  }

  .detail-footer {
    display: flex;
    gap: 12px;
    padding: 10px;
    background-color: #ffffff;
    border-top: 1px solid #e0e0e0;

    .cancel-btn,
    .confirm-btn {
      flex: 1;
      padding: 4px;
      font-size: 15px;
      font-weight: 500;
      border: none;
      border-radius: 8px;
      cursor: pointer;
    }

    .cancel-btn {
      background-color: #f5f5f5;
      color: #666;

      &:active {
        background-color: #e0e0e0;
      }
    }

    .confirm-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #ffffff;

      &:active {
        opacity: 0.9;
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
